import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/lastAccess")
public class LastAccessServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // 获取所有的 cookie
        Cookie[] cookies = request.getCookies();
        Cookie lastAccessCookie = null;

        if (cookies != null) {
            // 遍历 cookie，查找名为 "lastAccess" 的 cookie
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("lastAccess")) {
                    lastAccessCookie = cookie;
                    break;
                }
            }
        }

        if (lastAccessCookie != null) {
            // 获取上次访问时间戳并转换为日期时间字符串
            long lastAccessTimeMillis = Long.parseLong(lastAccessCookie.getValue());
            Date lastAccessDate = new Date(lastAccessTimeMillis);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String lastAccessTimeString = dateFormat.format(lastAccessDate);

            out.println("上次访问时间：" + lastAccessTimeString);
        } else {
            // 创建一个新的 cookie，存储当前时间戳，并发送给客户端
            long currentTime = System.currentTimeMillis();
            Cookie newCookie = new Cookie("lastAccess", String.valueOf(currentTime));
            newCookie.setMaxAge(3600); // 设置 cookie 存活时间为 1 小时
            response.addCookie(newCookie);
            out.println("欢迎首次访问！");
        }
    }
}